package ajjj.kiviq.beans;

import ajjj.kiviq.entities.*;
import ajjj.kiviq.remoteInterfaces.IRemoteCategory;
import java.util.List;
import java.util.ArrayList;
import java.io.*;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

/**
 *  Updated 2011-10-11 by jonatan
 *  - Added removal of questions functionality
 * 
 *  Handles the input from the manage.xhtml page
 * 
 * @author jeklund
 */
@ManagedBean(name = "newCat")
@ViewScoped
public class ManageCategoryBean {

    @EJB
    private IRemoteCategory cf;
    private Category cat;
    private List<Question> questions;
    private List<Alternative> alternatives;
    private String catTitle;
    private String questionTitle;
    private String questionImage;
    private String content;
    private Boolean correct;
    private Boolean pub;
    private String addQError;
    private String addAltError;
    private String addCatError;
    @ManagedProperty(value = "#{DateBean.currentDateTime}")
    private String created;
    @ManagedProperty(value = "#{UserBean}")
    private UserBean ub;

    /** Creates a new instance of NewCategoriesManagedBean */
    public ManageCategoryBean() {
    }

    @PostConstruct
    public void init() {
	HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
	String id = req.getParameter("id");
	if (id == null && cat == null) {
	    cat = new Category();
	    questions = new ArrayList<Question>();
	    alternatives = new ArrayList<Alternative>();
	} else {
	    loadCategory(id);
	}
    }

    public void loadCategory(String idString) {
	cat = new Category();
	questions = new ArrayList<Question>();
	alternatives = new ArrayList<Alternative>();
	try {
	    Long id = Long.parseLong(idString);
	    loadCategory(cf.getCategory(id));

	} catch (Exception e) {
	}
    }

    public void loadCategory(Category c) {
	cat.setId(c.getId());
	catTitle = c.getTitle();
	long i = 0;
	for (Question q : c.getQuestions()) {
	    q.setId(i++);
	    questions.add(q);
	}
	pub = c.isPublic();
    }

    public String getAddAltError() {
	String ret = addAltError;
	addAltError = "";
	return ret;
    }

    public void setAddAltError(String addAltError) {
	this.addAltError = addAltError;
    }

    public String getAddCatError() {
	String ret = addCatError;
	addCatError = "";
	return ret;
    }

    public void setAddCatError(String addCatError) {
	this.addCatError = addCatError;
    }

    public String getAddQError() {
	String ret = addQError;
	addQError = "";
	return ret;
    }

    public void setAddQError(String addQError) {
	this.addQError = addQError;
    }

    public String getQuestionImage() {
	return questionImage;
    }

    public void setQuestionImage(String questionImage) {
	this.questionImage = questionImage;
    }

    public void removeQuestionImage() {
	try {
	    File root = new File(
		    FacesContext.getCurrentInstance().getExternalContext().getRealPath("images"));
	    new File(root, questionImage).delete();
	} catch (Exception e) {
	}
	setQuestionImage(null);
    }

    public void removeQuestion(Question q) {
	questions.remove(q);
    }

    public List<Alternative> getAlternatives() {
	return alternatives;
    }

    public void setAlternatives(List<Alternative> alternatives) {
	this.alternatives = alternatives;
    }

    public Category getCat() {
	return cat;
    }

    public void setCat(Category cat) {
	this.cat = cat;
    }

    public List<Question> getQuestions() {
	return questions;
    }

    public void setQuestions(List<Question> questions) {
	this.questions = questions;
    }

    public String getCatTitle() {
	return catTitle;
    }

    public void setCatTitle(String catTitle) {
	this.catTitle = catTitle;
    }

    public String getquestionTitle() {
	return questionTitle;
    }

    public void setquestionTitle(String qTitle) {
	this.questionTitle = qTitle;
    }

    public String getContent() {
	return content;
    }

    public void setContent(String content) {
	this.content = content;
    }

    public Boolean getCorrect() {
	return correct;
    }

    public void setCorrect(Boolean correct) {
	this.correct = correct;
    }

    public Boolean getPub() {
	return pub;
    }

    public String getCreated() {
	return created;
    }

    public void setCreated(String created) {
	this.created = created;
    }

    public void setPub(Boolean pub) {
	this.pub = pub;
    }
    
    public boolean areAnyCorrectAlts() {
	for (Alternative a : alternatives)
	    if (a.isRight())
		return true;
	return false;
    }

    public UserBean getUb() {
        return ub;
    }

    public void setUb(UserBean ub) {
        this.ub = ub;
    }
    
    public void addAltToQ() {
	content = content.trim();
	if (content.isEmpty()) {
	    setAddAltError("Please supply alternative text");
	    return;
	} else if (areAnyCorrectAlts() && correct) {
	    setAddAltError("There is already a correct alternative");
	    return;
	}

	Alternative alt = new Alternative();
	alt.setContent(content);
	alt.setRight(correct);
	alternatives.add(alt);
	content = "";
	correct = false;
    }

    public void addQToCat() {
	questionTitle = questionTitle.trim();
	if (questionTitle.isEmpty()) {
	    setAddQError("Please supply question text");
	    return;
	} else if (alternatives.size() <= 1) {
	    setAddQError("There should be atleast two alternatives");
	    return;
	} else if (!areAnyCorrectAlts()) {
	    setAddQError("There are no correct alternatives");
	    return;
	}
	
	Question question = new Question();
	question.setId((long) questions.size());
	question.setTitle(questionTitle);
	question.setAlternatives(alternatives);
	if (questionImage != null) {
	    Image img = new Image();
	    img.setUri(questionImage);
	    question.setImage(img);
	}

	alternatives = new ArrayList<Alternative>();
	questions.add(question);
	questionTitle = "";
	questionImage = null;
    }

    public String saveCat() {
	catTitle = catTitle.trim();
	if (catTitle.isEmpty()) {
	    setAddCatError("Please supply a category name");
	    return null;
	} else if (questions.isEmpty()) {
	    setAddCatError("There are no questions");
	    return null;
	}
	
	cat.setTitle(catTitle);
	cat.setPublic(pub);
	cat.setCreated(created);
	for (Question q : questions) {
	    for (Alternative a : q.getAlternatives()) {
		a.setId(null);
	    }
	    if (q.getImage() != null)
		q.getImage().setId(null);
	    
	    q.setId(null);
	    cat.addQuestion(q);
	}

	String user = ub.currentUser();
	cf.addCategory(cat, user);
	return "category.jsf?faces-redirect=true";
    }
}
